package com.sdjzu.wanfuying.androiddesign.mvvm.student;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.sdjzu.wanfuying.androiddesign.BR;
import com.sdjzu.wanfuying.androiddesign.R;
import com.sdjzu.wanfuying.androiddesign.base.BaseActivity;

import java.util.ArrayList;
import java.util.List;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import butterknife.BindView;

public class StudentListActivity extends BaseActivity {
    @BindView(R.id.activity_student_list_listview)
    ListView mListView;

    private StudentListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_student_list);
        adapter = new StudentListAdapter();
        mListView.setAdapter(adapter);
        loopOnUiThread(() -> adapter.refresh(), 1000, 1000);
    }

    class StudentListAdapter extends BaseAdapter {
        private final static int STUDENT_NUM = 10;
        private List<Student> studentList = new ArrayList<>(STUDENT_NUM);

        public StudentListAdapter() {
            studentList.clear();
            for (int i = 0; i < STUDENT_NUM; i++) {
                Student student = new Student("2014000" + i, Math.random() + "");
                student.setAvatarUrl("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1548663767481&di=273eafa024cfdbcb29764b0dfaa66fde&imgtype=0&src=http%3A%2F%2Fpic23.nipic.com%2F20120904%2F6772262_115609168000_2.jpg");
                studentList.add(student);
            }
        }

        public void refresh() {
            for (Student student : studentList) {
                student.setName(Math.random() + "");
            }
        }

        @Override
        public int getCount() {
            return studentList.size();
        }

        @Override
        public Student getItem(int position) {
            return studentList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewDataBinding viewDataBinding;
            if (null == convertView) {
                viewDataBinding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_student_list_item, parent, false);
            } else {
                viewDataBinding = DataBindingUtil.getBinding(convertView);
            }
            assert viewDataBinding != null;
            viewDataBinding.setVariable(BR.student, getItem(position));
            return viewDataBinding.getRoot().getRootView();
        }
    }
}
